#!/usr/bin/env python
import time
import re

def get_now(fmt='%Y-%m-%d %X'):
    return time.strftime(fmt,time.localtime(time.time()))
    
def get_today(sep='-'):
    fmt=sep.join(['%Y','%m','%d'])
    return time.strftime(fmt,time.localtime(time.time()))
    
def get_yesterday(sep='-'):
    fmt=sep.join(['%Y','%m','%d'])
    return time.strftime(fmt,time.localtime(time.time()-24*60*60))
    
def format_date(date,sep='-'):
    m=re.compile(r'^(\d{4})([-/])?(\d{2})([-/])?(\d{2})$').match(date)
    #m=re.match('^(\d{4})([-/])?(\d{2})([-/])?(\d{2})$',date)
    if m:
        return sep.join(m.group(1,3,5))
    else:
        return get_yesterday()
        
def var_date(date,sep='-',flag='+',interval=1):
    date=format_date(str(date),sep)
    fmt=sep.join(['%Y','%m','%d'])
    if flag=='+':
        return time.strftime(fmt,time.localtime(time.mktime(time.strptime(date,fmt))+interval*24*60*60))
    elif flag=='-':
        return time.strftime(fmt,time.localtime(time.mktime(time.strptime(date,fmt))-interval*24*60*60))
    else:
        return date
        
def get_last_week(date):
    return var_date(date,flag='-',interval=7)
    
def get_last_month(date):
    return var_date(date,flag='-',interval=30)
    
def get_last_year(date):
    return var_date(date,flag='-',interval=365)
    
def get_last_hour():
    return time.strftime('%H',time.localtime(time.time()-60*60))
    
def format_hour(hour):
    m=re.match('^(\d{1,2})$',str(hour))
    if m:
        h=m.group(1)
        if int(h)<10:
            return '0'+str(h)
        else:
            return h
    else:
        return get_last_hour()
        
def get_date_info(date,fmt='%Y'):
    date=format_date(str(date))
    sth=time.strftime(fmt,time.localtime(time.mktime(time.strptime(date,'%Y-%m-%d'))))
    if fmt=='%Y':
        return sth
    elif fmt=='%m' or fmt=='%d':
        return int(sth)
    elif fmt=='%W':
        return int(sth)+1
    elif fmt=='%w':
        if sth=='0':
            sth=7
        return sth
    else:
        return time.strftime('%Y%m%d',time.localtime(time.mktime(time.strptime(date,'%Y-%m-%d'))))
    


